"""
此处存放与数据库交互的数据
"""

import os
from conf import settings

# 查看数据
def select(username):
    with open(settings.DB_TXT_PATH,'r',encoding='utf-8') as f:
        for line in f:
            if username in line:
                user_data = line.strip().split(':')
                return user_data

# 保存数据
def save(username,password,balance=0):
    with open(settings.DB_TXT_PATH,'a',encoding='utf-8') as f:
        f.write(f'{username}:{password}:{balance}\n')

# 更新数据
def update(old_data,new_data):
    import os
    New_path = os.path.join(
        settings.DB_PATH,'new.txt'
    )
    with open(settings.DB_TXT_PATH,'r',encoding='utf-8') as r_f,\
        open(New_path,'w',encoding='utf-8') as w_f:
        all_user_data = r_f.read()
        all_user_data = all_user_data.replace(old_data,new_data)

        w_f.write(all_user_data)

    os.remove(settings.DB_TXT_PATH)
    os.rename(New_path,settings.DB_TXT_PATH)

# 获取小说数据
def get_all_story():
    with open(settings.STORY_PATH,'r',encoding='utf-8') as f:

        story_dic = eval(f.read())
        return story_dic

# 查看小说路径
def show_fiction_data(fiction_name):
    # 获取小说路径
    fiction_path = os.path.join(
        settings.FICTION_DIR,fiction_name
    )

    # 打开文件，获取文件数据，并返回给用户展示
    with open(fiction_path,'r',encoding='utf-8') as f:
        fiction_data = f.read()

    return fiction_data
